package com.zwl.springcloud.Interceptor;

import com.zwl.springcloud.utlis.JSONUtils;
import com.zwl.springcloud.utlis.TokenUtil;
import com.zwl.springcloud.annotation.EnableAuth;
import com.zwl.springcloud.config.RedisUtil;
import com.zwl.springcloud.entity.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/** 自定义token拦截器 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource private RedisUtil redisUtil;

    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        Method method = ((HandlerMethod) handler).getMethod();
        EnableAuth enableAuth = method.getAnnotation(EnableAuth.class);
        if (enableAuth == null) {
            return true;
        }

        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("admin-token");
        if (token != null) {
            String username = TokenUtil.getAccount(token);
            String cachedToken = redisUtil.get("user:session:" + username);
            if (cachedToken == null || !cachedToken.equals(token)) {
                response.getWriter().write("50000");
                response.setStatus(401);
                return false;
            }

            boolean result = TokenUtil.verify(token);
            if (result) {
                System.out.println("通过拦截器");
                return true;
            }
        }

        System.out.println("认证失败,请重新登录");
        response.setStatus(401);
        String string = JSONUtils.toJson(new Result<>("认证失败", 401, "token过期"));
        response.getWriter().write(string);

        return false;
    }
}
